<?php defined('SYSPATH') or die('No direct script access.');

class Controller_App extends Controller_Template {

	public $template = 'templates/app';
	
	public $view;
	private $store;
	
	public $styles = array();
	public $scripts = array();
	
	public $auth_required = FALSE;
	public $secure_actions = FALSE;
	
	public function before(){
		parent::before();
		
		#Open session
	    $this->session = Session::instance();
	 
	    #Check user auth and role
	    $action_name = $this->request->action();
	    if (($this->auth_required !== FALSE && Auth::instance()->logged_in($this->auth_required) === FALSE)
	    || (is_array($this->secure_actions) && array_key_exists($action_name, $this->secure_actions) && 
	    Auth::instance()->logged_in($this->secure_actions[$action_name]) === FALSE)){
			if (Auth::instance()->logged_in()){
				$this->request->redirect('user/noaccess');
			}else{
				$this->request->redirect('user/login_register?url=');
			}
		}
		
		#Set current Store
		$app_config = Kohana::config('app.default');
		
		$store = $this->request->param('store', NULL);
		
		if(!is_null($store)){
			$this->store = Model::factory('store')->where('name', '=', strtolower($store))->find();
			if($this->store->loaded()){
				$this->template->title = $this->store->title;
				$this->template->meta_keywords = $this->store->meta_keywords;
				$this->template->meta_description = $this->store->meta_description;
			}else{
				$this->store = NULL;
				$this->request->redirect(URL::site('site/createStore?newstore=' . $store));
			}
		}else{
			$this->request->redirect(URL::base());
		}
		
		$this->template->meta_copyright = $app_config['meta_copyright'];
		
		if(isset($this->view)){
			$this->view = new View($this->view);
		}
	}

	public function after(){
		$app_config = $this->getAppConfig();
		$this->template->styles = array_merge( $this->styles, $app_config['styles']);
		$this->template->scripts = array_merge( $this->scripts, $app_config['scripts']);
		
		if(isset($this->view)){
			$this->template->content = $this->view;
		}

		parent::after();
	}
	
	public function getStore(){
		return isset($this->store) ? $this->store : NULL;
	}
	
	public function storeIsSet(){
		return !is_null($this->store);	
	}
	
	public function getURLStore($url = NULL){
		return URL::site($this->getStore()->name) . '/' . $url;	
	}
	
	public function getAppConfig(){
		return Kohana::config('app.default');
	}

}